<template>
	<view class="content" v-if="order !== null">
		<view class="card order-status">
			<view class="order-code">
				<view>
					订单号：{{ order.order_code }}
				</view>


				<uni-tag v-if="order.status === 1 && order.payment_status === 1" type="warning" text="等待支付" />

				<uni-tag v-if="order.status === 1 && order.payment_status === 2 && order.shipping_status === 1"
					type="warning" text="等待配送" />

				<uni-tag v-if="order.status === 1 && order.payment_status === 2 && order.shipping_status === 2"
					type="warning" text="配送中" />

				<uni-tag v-if="order.status === 2" text="已完成" />

				<uni-tag v-if="order.status === 3 && order.payment_status === 1" text="已取消" />

				<uni-tag v-if="order.status === 3 && order.payment_status === 3" text="已退款" />
			</view>

			<view style="padding:24px 0 12px 0;">
				<uni-steps :options="orderSteps" :active="currentSteps" />
			</view>


		</view>

		<view class="card delivery-person" v-if="order.delivery_person">
			<uni-section title="配送员">
				<view style="display: flex;align-items: center;padding: 4px 0;">
					<uni-icons type="person" style="line-height: 1;margin-right: 4px;"></uni-icons>
					<text>{{order.delivery_person.name}}</text>
				</view>
			</uni-section>
			<uni-section title="联系电话">
				<view style="display: flex;align-items: center;padding: 4px 0;">
					<uni-icons type="phone" style="line-height: 1;margin-right: 4px;"></uni-icons>
					<text>{{order.delivery_person.phone}}</text>
				</view>
			</uni-section>
		</view>

		<view class="card shipping-address" v-if="order.delivery_address">
			<view>
				<view>
					<label class="label">
						收花人
					</label>
					<text style="font-weight: 700;margin-left: 12px;">{{ order.delivery_address.recipient }}</text>
					<text style="font-weight: 700;margin-left: 12px;">{{ order.delivery_address.phone }}</text>
				</view>
				<view style="color: #999;font-size: 14px;margin-top: 10px;">
					{{ `${order.delivery_address.province} ${order.delivery_address.city} ${order.delivery_address.district} ${order.delivery_address.details_address}` }}
				</view>
			</view>
		</view>

		<view class="card" style="display: flex;align-items: center;">
			<label>
				订花人电话
				<uni-icons type="help"></uni-icons>
			</label>
			<view style="flex:1;padding: 0 10px;font-size: 14px;">{{ order.customer_phone }}</view>
			<uni-icons custom-prefix="iconfont" type="icon-phone" color="#07c484"></uni-icons>
		</view>

		<view class="card greeting-card" v-if="order.greeting_card">
			<view style="display: flex;align-items: center;justify-content: space-between;">
				<text>贺卡文字</text>
			</view>
			<view class="greeting-card-content">
				{{ order.greeting_card }}
			</view>
		</view>

		<view class="card product-card">
			<view class="product-list">
				<view class="product-item" v-for="(product,index) in order.items" :key="product.id">
					<image :src="getFlowerCover(product.flower.images)" class="cover"></image>
					<view class="info">
						<view class="name">{{ product.flower.name }}</view>
						<view class="price">{{ "￥" + numeral(product.flower.price).format("0.00") }}</view>
						<view class="quantity">{{ `x ${product.quantity}` }}</view>
					</view>
				</view>
			</view>
			<view class="subtotal">
				{{ `小计 ￥${numeral(order.subtotal).format("0.00")}` }}
			</view>
		</view>

		<view class="card">
			<uni-forms label-position="top">
				<uni-forms-item label="收货方式">
					<uni-data-checkbox v-model="order.delivery_method" mode="tag"
						:localdata="deliveryMethodOption"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item :label="order.delivery_method === 1?'配送时间':'取货时间'">
					<view v-if="order.delivery_date" style="display: flex;align-items: center;">
						<uni-icons type="calendar" :size="18" style="line-height: 1;margin-right: 4px;"></uni-icons>
						{{ dayjs(order.delivery_date).format("YYYY-MM-DD HH:mm:ss") }}
					</view>
					<view v-else>
						<uni-tag :text="formData.delivery_method === 1?'立即配送':'立即取货'" type="primary">
						</uni-tag>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>

		<view class="card notes-card" v-if="order.notes">
			<view>
				订单备注
			</view>
			<view class="notes-card-content">
				{{ order.notes }}
			</view>
		</view>

		<view class="card warn-card">
			<view class="warn-card-title">
				<uni-icons type="info-filled" color="#ee7566" :size="24"></uni-icons>
				温馨提示
			</view>
			<view class="warn-card-content">
				鲜花属于鲜活易腐类产品，花束一经包扎或发起配送后则影响二次销售。鲜花产品不支持7天无理由退换货。
			</view>
		</view>

		<view :style="{height:safeAreaBottom+60+'px'}"></view>

		<view class="footer" :style="{'paddingBottom':safeAreaBottom+'px'}" v-if="order.status !== 3">
			<view class="footer-content">
				<button type="primary" size="mini" v-if="order.status === 1 && order.payment_status === 1"
					@click="handlePayment(order.id)">立即付款</button>
				<button size="mini" v-if="order.status === 1 && order.payment_status === 1"
					@click="handleCancelOrder(order)">取消订单</button>

				<button type="primary" size="mini" v-if="order.status === 1 && order.payment_status === 2"
					@click="handleConfirmReceipt(order)">确认收货</button>

				<button size="mini"
					v-if="order.status === 1 && order.payment_status === 2 && order.shipping_status === 1"
					@click="handleRefundOrder(order)">申请退款</button>
			</view>
		</view>
	</view>
	<PaymentModal ref="paymentModalRef" @paid="loadOrder" />
</template>

<script setup>
	import numeral from 'numeral';
	import {
		computed,
		nextTick,
		onMounted,
		reactive,
		ref
	} from "vue"
	import {
		AddressPageMode
	} from "@/constants/index.js"
	import {
		useOrderStore
	} from "@/stores/order.js"
	import {
		onLoad,
		onReady
	} from "@dcloudio/uni-app"
	import {
		useUserStore
	} from "@/stores/user.js"
	import {
		getFlowerCover
	} from "@/utils/index.js"
	import {
		SERVER_URL
	} from "@/config/index.js"
	import dayjs from 'dayjs';
	import PaymentModal from './components/PaymentModal.vue';

	const userStore = useUserStore()
	const orderStore = useOrderStore()

	const safeAreaBottom = ref(0)

	const toAddressPage = () => {
		let url = "/pages/user/address?mode=" + AddressPageMode.SELECT
		if (order.delivery_address && order.delivery_address.id) {
			url += "&selected=" + order.delivery_address.id
		}
		uni.navigateTo({
			url
		})
	}

	const state = reactive({
		greetingCard: true,
		orderId: null,
		showPayment: false
	})

	const orderSteps = ref([{
		title: '备货中'
	}, {
		title: '配送中'
	}, {
		title: computed(() => {
			if (order.value && order.value.status === 3) {
				return "已取消"
			}
			return '已完成'
		})
	}])

	const currentSteps = computed(() => {
		if (order.value) {
			if (order.value.status === 2 || order.value.status === 3) {
				return 2
			}
			if (order.value.payment_status === 2 && order.value.shipping_status === 2) {
				return 1
			}
			if (order.value.payment_status === 2) {
				return 0
			}
		}

		return -1
	})

	const order = ref(null)

	const loadOrder = () => {
		uni.showLoading({
			title: "加载订单..."
		})
		uni.request({
			url: SERVER_URL + '/customer/order/detail/' + state.orderId,
			method: "GET",
			header: {
				"authorization": userStore.token
			},
			success: (res) => {
				if (res.statusCode === 200) {
					order.value = res.data
					console.log(order.value)
				}
			},
			complete: () => {
				uni.hideLoading()
			}
		});
	}

	const subtotal = computed(() => {
		const total = numeral(0)

		orderStore.products.forEach((item) => {
			const price = numeral(item.quantity).multiply(item.flower.price).value()
			total.add(price)
		})

		return total.value()
	})

	const totalPrice = computed(() => {
		const total = numeral(0)

		orderStore.products.forEach((item) => {
			const price = numeral(item.quantity).multiply(item.flower.price).value()
			total.add(price)
		})

		return total.value()
	})

	const deliveryMethodOption = computed(() => {
		if (order.value) {
			if (order.value.delivery_method === 1) {
				return [{
					text: '商家配送',
					value: 1
				}]
			} else {
				return [{
					text: '到店自提',
					value: 2,
					disabled: true
				}]
			}
		}

		return []
	})

	const startDeliveryDate = computed(() => {
		if (orderStore.presale_delivery_date) {
			return dayjs(orderStore.presale_delivery_date).startOf("d").format("YYYY-MM-DD HH:mm:ss")
		}

		return dayjs().endOf("minute").add(30, "minute").format("YYYY-MM-DD HH:mm:ss")
	})

	const formData = reactive({
		phone: undefined,
		notes: undefined,
		greeting_card: undefined,
		delivery_method: 1,
		delivery_date: undefined
	})

	const handleSwitchGreetingCard = (e) => {
		state.greetingCard = e.detail.value
		if (!state.greetingCard) {
			formData.greeting_card = undefined
		}
	}

	const paymentModalRef = ref()
	const handlePayment = (id) => {
		paymentModalRef.value.show(id)
	}

	const handleCancelOrder = (order) => {
		uni.showModal({
			title: "确认要取消订单？",
			success: (res) => {
				if (res.confirm) {
					uni.showLoading()
					uni.request({
						url: SERVER_URL + '/customer/order/cancel/' + order.id,
						method: "PUT",
						header: {
							"content-type": "application/json",
							"authorization": userStore.token
						},
						success: (res) => {
							if (res.statusCode === 200) {
								uni.showToast({
									icon: "success",
									title: "订单已取消"
								})

								setTimeout(() => {
									loadOrder()
								}, 500)
							}
						},
						complete: () => {
							uni.hideLoading()
						}
					});
				}
			}
		})
	}

	const handleConfirmReceipt = (order) => {
		uni.showModal({
			title: "确认已收到商品？",
			success: (res) => {
				if (res.confirm) {
					uni.showLoading()
					uni.request({
						url: SERVER_URL + '/customer/order/confirm-receipt/' + order.id,
						method: "PUT",
						header: {
							"content-type": "application/json",
							"authorization": userStore.token
						},
						success: (res) => {
							if (res.statusCode === 200) {
								uni.showToast({
									icon: "success",
									title: "订单已完成"
								})

								setTimeout(() => {
									loadOrder()
								}, 500)
							}
						},
						complete: () => {
							uni.hideLoading()
						}
					});
				}
			}
		})
	}

	onLoad((e) => {
		const windowInfo = uni.getWindowInfo()
		safeAreaBottom.value = windowInfo.safeAreaInsets.bottom

		if (e.id) {
			state.orderId = Number(e.id)
			state.showPayment = Boolean(e.payment)
			loadOrder()
		} else {
			uni.navigateBack()
		}
	})

	onMounted(() => {
		nextTick(() => {
			if (state.orderId && state.showPayment) {
				handlePayment(state.orderId)
			}
		})
	})
</script>

<style scoped lang="scss">
	.content {
		min-height: 100vh;
		background: #F2F6FD;
		padding: 12px;

		.card {
			border-radius: 6px;
			background-color: #fff;
			margin-bottom: 12px;
			padding: 12px;

			:deep(.uni-forms-item) {
				margin-bottom: 0;
			}
		}

		.order-status {
			.order-code {
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-bottom: 1px solid #efefef;
				padding-bottom: 10px;
			}

			uni-tag {
				display: inline-flex;
			}
		}

		.delivery-person {
			:deep(.uni-section) {
				.uni-section-header {
					padding: 2px 0;
				}
			}
		}

		.shipping-address {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.label {
				border: 1px solid #e75d58;
				color: #e75d58;
				padding: 2px 4px;
				border-radius: 4px;
				font-size: 0.875rem;
			}

			.placeholder {
				display: flex;
				align-items: center;
				justify-content: center;
				color: #666;

				.uni-icons {
					margin-left: 2px;
					vertical-align: middle;
				}
			}
		}

		.greeting-card {
			.greeting-card-content {
				margin-top: 12px;
				font-size: 14px;
				background-color: #ffeeee !important;
				border-color: #ffeeee !important;
				padding: 6px;
				border-radius: 4px;
			}

			:deep(.uni-easyinput) {
				.uni-easyinput__content {
					background-color: #ffeeee !important;
					border-color: #ffeeee !important;
				}
			}
		}

		.product-card {
			.product-list {
				.product-item {
					margin-top: 12px;
					display: flex;
					align-items: center;

					.cover {
						width: 80px;
						height: 80px;
						margin-right: 10px;
					}

					.info {
						flex: 1;
						height: 80px;
						display: flex;
						flex-direction: column;
						overflow: hidden;

						.name {
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}

						.price {
							margin-top: 12px;
							color: #ee0a24;
						}

						.quantity {
							font-size: 14px;
							color: #666;
							text-align: right;
						}
					}
				}
			}

			.subtotal {
				border-top: 1px solid #eeeeee;
				margin-top: 12px;
				padding-top: 12px;
				text-align: right;
				font-weight: 700;
			}
		}

		.notes-card {
			.notes-card-content {
				margin-top: 12px;
				font-size: 14px;
				color: #333;
				padding: 6px;
				background-color: #f7f7f7;
				border-radius: 4px;
			}
		}

		.warn-card {
			background: linear-gradient(to bottom, #fcf6f4 0%, #ffffff 100%);

			.warn-card-title {
				margin-bottom: 12px;
				display: flex;
				align-items: center;
			}

			.warn-card-content {
				color: #a2a7aa;
				font-size: 12px;
			}
		}

		.footer {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			background-color: #fff;
			box-shadow: 0px -2px 4px 2px rgba(0, 0, 0, 0.1);

			.footer-content {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 12px;
				gap: 12px;

				button {
					margin: 0;
				}
			}
		}
	}
</style>